package net.coding.api.test.helper;


import com.jcraft.jsch.KeyPair;
import io.restassured.response.Response;
import net.coding.api.test.TestClient;

import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

import static io.restassured.path.json.JsonPath.with;
import static net.coding.api.test.ApiMethod.POST;
import static net.coding.api.test.TestHelper.getCurrentUser;
import static net.coding.api.test.TestHelper.userHelper;
import static org.hamcrest.Matchers.equalTo;

/**
 * Created with IntelliJ IDEA.
 * User: chenfeilong
 * Date: 2018/1/17
 * Time: 15:54
 * Description: Git相关操作
 */
public interface BaseGitHelper {

    /**
     * 添加公钥
     *
     * @param title
     * @param keyPair
     * @return
     */
    default Integer addPublicKey(String title, KeyPair keyPair) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = formatter.format(new Date());
        String pubKey = "ssh-rsa " + new String(Base64.getEncoder().encode(keyPair.getPublicKeyBlob())) + " rsa-key-" + dateStr;
        // POST /user/:globalKey/keys
        Response response = TestClient.client().login()
                .param("title", title)
                .param("content", pubKey)
                .param("password", userHelper.getPassword(true))
                .request(POST, String.format("/user/%s/keys", userHelper.getPersonalGlobalKey())).returnedCode(0).response();

        response.then().assertThat()
                .body("data.title", equalTo(title))
                .body("data.owner_id", equalTo(getCurrentUser().getId()));
        return with(response.asString()).getInt("data.id");
    }


    /**
     * 删除公钥
     *
     * @param keyId
     */
    default void deletePublicKey(Integer keyId) {
        TestClient.client().login()
                .param("password", userHelper.getPassword(true))
                .request(POST, String.format("/user/%s/key/%d/delete", userHelper.getPersonalGlobalKey(), keyId)).returnedCode(0);
    }


    /**
     * 获取depot信息
     *
     * @param projectName
     * @return
     */
    String getGitDepotPath(String projectName);

    /**
     * 获取打包请求URI
     *
     * @param projectName
     * @param ref
     * @return
     */
    String getArchiveUri(String projectName, String ref);

    /**
     * 获取RawBlobUri
     *
     * @param projectName
     * @param ref
     * @param path
     * @return
     */
    String getRawBlobUri(String projectName, String ref, String path);

}
